package com.haiheng.module_main.fragment

import android.annotation.SuppressLint
import android.app.ScansManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.haiheng.common.dialog.StandardDialog
import com.haiheng.common.fragment.RouterFragment
import com.haiheng.library.log.LogUtils
import com.haiheng.library_base.dialog.LoadingDialog
import com.haiheng.library_base.model.ApplicationViewModel
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.msg.MsgCode
import com.haiheng.library_base.msg.MsgEvent
import com.haiheng.library_base.toast.ToastUtils
import com.haiheng.library_base.utils.FastClickUtil
import com.haiheng.module_main.R
import com.haiheng.module_main.bean.res.QueryBookAcsResult
import com.haiheng.module_main.databinding.FragmentSmartEploymentBinding
import com.haiheng.module_main.mode.BookInfoViewModel
import com.haiheng.module_main.mode.DeploymentViewModel


/**
 *
 * @Des:智慧上架
 * @Author: hwz
 * @Date:2023/6/17 0017
 * @Version: 1.0
 */
class SmartEploymentFragment : RouterFragment() {
    private lateinit var binding:FragmentSmartEploymentBinding
    private val viewModel : BookInfoViewModel by viewModels()
    private lateinit var deploymentViewModel: DeploymentViewModel
    private lateinit var loadingDialog : LoadingDialog
    private var mScansManager: ScansManager? = null
    private var layerInfoSureDialog  : StandardDialog? = null
    private var sureStartAndEndDialog  : StandardDialog? = null

    private val observer = Observer<MsgEvent> { msgEvent ->
        onMessageChange(msgEvent)
    }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentSmartEploymentBinding.inflate(inflater,container,false)
        // Inflate the layout for this fragment
        return binding.root
    }

    @SuppressLint("WrongConstant")
    override fun initView() {
        deploymentViewModel = DeploymentViewModel(viewModel)
        var manager = activity.getSystemService("scans")
        if (manager != null) {
            mScansManager = manager as ScansManager
            mScansManager?.persistMode = true
        }
        loadingDialog = LoadingDialog(requireContext(), R.style.AvLoadingDialogStyle)
        binding.includeBottom.cbAll.visibility = View.GONE
        binding.includeTile.ivBack.setOnClickListener {
            activity.navigateUp()
        }
        binding.includeTile.cbRignt.isChecked = false
        binding.includeIdentifyShelf.cbGetShelfNo.isChecked = true
        binding.includeTile.cbRignt.setOnClickListener {
            binding.includeTile.cbRignt.isChecked = true
            binding.includeIdentifyShelf.cbGetShelfNo.isChecked = false
        }
        binding.includeIdentifyShelf.cbGetShelfNo.setOnClickListener {
            binding.includeTile.cbRignt.isChecked = false
            binding.includeIdentifyShelf.cbGetShelfNo.isChecked = true
//            mScansManager?.startScan()
        }

        binding.includeIdentifyShelf.etShelfNo.setOnEditorActionListener {  v, keyCode, event ->
            LogUtils.e("ddddddd  keyCode${keyCode}")
            if(keyCode == EditorInfo.IME_ACTION_SEARCH) {
                binding.tvShelfInfo.text = ""
                viewModel.getShelName(binding.includeIdentifyShelf.etShelfNo.text.toString())
                false
            }
            false
        }
        binding.includeBottom.btnClear.setOnClickListener {
            binding.tvEndInfo.setText("")
            binding.tvStartInfo.setText("")
            viewModel._bookListData.postValue(listOf())
        }
        binding.includeBottom.btnSubmit.setOnClickListener {
            var layNo = binding.includeIdentifyShelf.etShelfNo.text.toString()
            loadingDialog.setMessage("上架中..")
            var onSelfObjType = 0
            if (binding.includeTile.rbTitleLeft.isChecked){
                onSelfObjType = 0
            }
            if (binding.includeTile.rbTitleRigh.isChecked){
                onSelfObjType = 1
            }
            if (layNo.isNotBlank()){
                deploymentViewModel.onSelfByCallNumber(layNo,onSelfObjType)
            }else{
                ToastUtils.showShort("架标号不能为空")
            }
        }
    }

    override fun initViewModel(): BaseViewModel? {
        viewModel.showMsg.observe(viewLifecycleOwner){
            ToastUtils.showShort(it)
            loadingDialog.hide()
        }
        viewModel.queryBookAcsRes.observe(viewLifecycleOwner){
            showSureStartAndEndDialog(it)
        }
        viewModel.layerInfo.observe(viewLifecycleOwner){
            var content = "层架号：${it.outValue} \n名称：${it.name}"
            if (layerInfoSureDialog == null){
                layerInfoSureDialog = StandardDialog.newInstance().setTitle(getString(R.string.hint_layer_no))
                    .setContent(content)
                    .setOnDialogListener(object : StandardDialog.OnDialogClickListener {
                        override fun onConfirm(dialog: StandardDialog) {
                            binding.tvShelfInfo.setText(it.name)
                            binding.includeTile.cbRignt.performClick()
                            dialog.dismiss()
                        }

                        override fun onCancel(dialog: StandardDialog) {
                            dialog.dismiss()
                        }
                    })
            }else{
                layerInfoSureDialog?.setContent(content)
            }
            if (!layerInfoSureDialog!!.isAdded){
                layerInfoSureDialog?.show(childFragmentManager)
            }

        }
        return deploymentViewModel
    }

    override fun initLoad() {

    }

    override fun onResume() {
        super.onResume()
        observEven()
    }
    override fun onPause() {
        super.onPause()
        clearMsg()
    }


    private fun onMessageChange(msgEvent: MsgEvent?) {
        when (msgEvent?.code){
            MsgCode.MSG_SCANS_BARCODE->{
                if (FastClickUtil.isFaskMsg(msgEvent.msg,200)) return //两次相同消息太快这不处理
                if (layerInfoSureDialog?.isVisible == true) return
                if (sureStartAndEndDialog?.isVisible == true) return
                if (binding.includeIdentifyShelf.cbGetShelfNo.isChecked){
                    binding.includeIdentifyShelf.etShelfNo.setText(msgEvent.msg)
                    binding.tvShelfInfo.text = ""
                    viewModel.getShelName(msgEvent.msg)
                }else if (binding.includeTile.cbRignt.isChecked){
                    viewModel.queryBookByAcs(msgEvent.msg)
                }


            }
        }
    }

    private fun observEven() {
        if (ApplicationViewModel.get().even != null) {
            if (ApplicationViewModel.get().even.hasObservers()) {
                ApplicationViewModel.get().even.removeObserver(observer)
            }
            ApplicationViewModel.get().even.observe(this,observer)
        }
    }
    fun clearMsg(){
        if (ApplicationViewModel.get().even != null) {
            if (ApplicationViewModel.get().even.hasObservers()) {
                ApplicationViewModel.get().even.removeObserver(observer)
            }
        }
    }

    fun showSureStartAndEndDialog(q: QueryBookAcsResult) {
        var content = "条码号：${q.bookSn} \n名称：${q.bookTitle} \n 索书号：${q.callNumber}"
        if (sureStartAndEndDialog == null){
            sureStartAndEndDialog = StandardDialog.newInstance().setTitle(getString(R.string.hint_sure_start_end))
                .setContent(content)
                .setData(q)
                .setLeftText("首书")
                .setRightText("末本")
                .setOnDialogListener(object : StandardDialog.OnDialogClickListener {
                    override fun onConfirm(dialog: StandardDialog) {
                        var data = dialog.getData() as QueryBookAcsResult
                        var endInfo =  "条码号：${data.bookSn} 名称：${data.bookTitle} \n 索书号：${data.callNumber}"
                        binding.tvEndInfo.setText(endInfo)
                        deploymentViewModel.endCallNu.postValue(data.callNumber)
                        dialog.dismiss()
                    }

                    override fun onCancel(dialog: StandardDialog) {
                        var data = dialog.getData() as QueryBookAcsResult
                        var starInfo =  "条码号：${data.bookSn} 名称：${data.bookTitle} \n 索书号：${data.callNumber}"
                        binding.tvStartInfo.setText(starInfo)
                        deploymentViewModel.startCallNu.postValue(data.callNumber)
                        dialog.dismiss()
                    }
                })
        }else{
            sureStartAndEndDialog?.setData(q)
            sureStartAndEndDialog?.setContent(content)
        }
        if (!sureStartAndEndDialog!!.isAdded){
            sureStartAndEndDialog?.show(childFragmentManager)
        }
    }
}